﻿using AutoMapper;
using B.MES.FLH.WarehouseManagement.Application.Dtos.Area;
using B.MES.FLH.WarehouseManagement.Application.Dtos.Definition;
using B.MES.FLH.WarehouseManagement.Application.Dtos.Externallabel;
using B.MES.FLH.WarehouseManagement.Application.Dtos.IOWarehouserecord;
using B.MES.FLH.WarehouseManagement.Application.Dtos.Location;
using B.MES.FLH.WarehouseManagement.Application.Dtos.Made_UpArticles;
using B.MES.FLH.WarehouseManagement.Domain.Entity;
using Dm.util;
using Infrastructure;
using Microsoft.AspNetCore.Http.HttpResults;
using Standard;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using Yitter.IdGenerator;

namespace B.MES.FLH.WarehouseManagement.Application
{
    public class Service : IService
    {
        private readonly MesRepository<WAREHOUSEDEFINITIONMODEL> _definitionRepo;
        private readonly MesRepository<AREAMODEL> _areaRepo;
        private readonly MesRepository<EXTERNALLABELMODEL> _externallabelRepo;
        private readonly MesRepository<LOCATION> _locationRepo;
        private readonly MesRepository<IOWAREHOUSERECORDMODEL> _ioRepo;
        private readonly MesRepository<Made_UpArticlesModel> _mduRepo;
        private readonly IMapper mapper;
        public Service(MesRepository<WAREHOUSEDEFINITIONMODEL> repository, IMapper mapper, MesRepository<AREAMODEL> areaRepo, MesRepository<EXTERNALLABELMODEL> externallabelRepo, MesRepository<LOCATION> locationRepo, MesRepository<IOWAREHOUSERECORDMODEL> ioRepo, MesRepository<Made_UpArticlesModel> mduRepo)
        {
            _definitionRepo = repository;
            this.mapper = mapper;
            _areaRepo = areaRepo;
            _externallabelRepo = externallabelRepo;
            _locationRepo = locationRepo;
            _ioRepo = ioRepo;
            _mduRepo = mduRepo;
        }
        //仓库定义模块
        public ApiResult<int> CreateWAREHOUSEDEFINITIONMODEL(CreateWarehouseDefinitionModelInput input)
        {

            //判断是否存在相同的仓库定义编码
            if (_definitionRepo.GetEntity(x => x.WAREHOUSEDEFINITIONCODE == input.WAREHOUSEDEFINITIONCODE) != null)
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.InternalError,
                    Message = "仓库定义编码已存在",
                    ResultData = 0
                };
            }
            var data = mapper.Map<WAREHOUSEDEFINITIONMODEL>(input);
            data.ID = YitIdHelper.NextId().ToString();
            data.ISDELETE = false;
            return new ApiResult<int>
            {
                Code = ApiCode.Success,
                ResultData = _definitionRepo.Add(data),
                Message = "添加成功"
            };

        }
        public ApiResult<int> DeleteWAREHOUSEDEFINITIONMODEL(string id)
        {

            var data = _definitionRepo.GetEntity(x => x.ID == id);
            if (data == null)
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.NotFound,
                    Message = "数据不存在"
                };
            }
            data.ISDELETE = true;
            int r = _definitionRepo.Update(data);
            return new ApiResult<int>
            {
                Code = r > 0 ? ApiCode.Success : ApiCode.InternalError,
                Message = r > 0 ? "删除成功" : "删除失败",
                ResultData = r
            };
        }
        public ApiResult<int> UpdateWAREHOUSEDEFINITIONMODEL(UpdateWarehouseDefinitionModelInput input)
        {
            var data = _definitionRepo.GetEntity(x => x.ID == input.ID);
            if (data == null)
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.NotFound,
                    Message = "数据不存在"
                };
            }
            data.UPDATETIME = DateTime.Now;
            var entity = mapper.Map(input, data);
            int r = _definitionRepo.Update(entity);
            return new ApiResult<int>
            {
                Code = r > 0 ? ApiCode.Success : ApiCode.InternalError,
                Message = r > 0 ? "修改成功" : "修改失败",
                ResultData = r
            };
        }
        public ApiPaging<WarehouseDefinitionModelOutput> GetWAREHOUSEDEFINITIONMODEL(PageWareHouseDefinition page)
        {
            var query = _definitionRepo.GetQueryable(x => x.ISDELETE == false);
            if (!string.IsNullOrEmpty(page.WAREHOUSEDEFINITIONCODE))
            {
                query = query.Where(x => x.WAREHOUSEDEFINITIONCODE.Contains(page.WAREHOUSEDEFINITIONCODE));
            }
            if (!string.IsNullOrEmpty(page.WAREHOUSENAME))
            {
                query = query.Where(x => x.WAREHOUSENAME.Contains(page.WAREHOUSENAME));
            }
            if (!string.IsNullOrEmpty(page.WAREHOUSETYPE))
            {
                query = query.Where(x => x.WAREHOUSETYPE == (page.WAREHOUSETYPE));
            }
            if (!string.IsNullOrEmpty(page.WAREHOUSEMANAGER))
            {
                query = query.Where(x => x.WAREHOUSEMANAGER.Contains(page.WAREHOUSEMANAGER));
            }
            if (!string.IsNullOrEmpty(page.WAREHOUSEADDRESS))
            {
                query = query.Where(x => x.WAREHOUSEADDRESS.Contains(page.WAREHOUSEADDRESS));
            }
            var totalCount = query.Count();
            var list = query.OrderByDescending(x => x.ID).Skip((page.PageIndex - 1) * page.PageSize).Take(page.PageSize).ToList();
            return new ApiPaging<WarehouseDefinitionModelOutput>
            {
                Code = ApiCode.Success,
                PageDatas = mapper.Map<List<WarehouseDefinitionModelOutput>>(list),
                Message = "查询成功",
                TotalCount = totalCount,
                TotalPage = (int)Math.Ceiling(totalCount / (double)page.PageSize)
            };
        }
        public ApiResult<WarehouseDefinitionDescOutput> GetWAREHOUSEDEFINITIONDESC(string id)
        {
            var data = _definitionRepo.GetEntity(x => x.ID == id && x.ISDELETE == false);
            var output = mapper.Map<WarehouseDefinitionDescOutput>(data);
            return new ApiResult<WarehouseDefinitionDescOutput>
            {
                Code = ApiCode.Success,
                Message = "查询成功",
                ResultData = output
            };
        }
        public ApiResult<List<GetWarehouseDefinitionIdAndName>> GetWarehouseDefinitionIdAndName()
        {
            return new ApiResult<List<GetWarehouseDefinitionIdAndName>>
            {
                Code = ApiCode.Success,
                Message = "查询成功",
                ResultData = _definitionRepo.GetQueryable(x => x.ISDELETE == false).Select(x => new GetWarehouseDefinitionIdAndName
                {
                    ID = x.ID,
                    WAREHOUSENAME = x.WAREHOUSENAME
                }).ToList()
            };
        }


        //货架库区模块
        public ApiResult<int> CreateAREAMODEL(CreateAreaModelInput input)
        {
            //判断是否存在相同的库位编码
            if (_areaRepo.GetEntity(x => x.AREAID == input.AREAID) != null)
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.InternalError,
                    Message = "库区编码已存在",
                    ResultData = 0
                };
            }
            var data = mapper.Map<AREAMODEL>(input);
            data.ID = YitIdHelper.NextId().ToString();
            data.CREATETIME = DateTime.Now;
            data.ISDELETE = false;
            return new ApiResult<int>
            {
                Code = ApiCode.Success,
                ResultData = _areaRepo.Add(data),
                Message = "添加成功"
            };
        }
        public ApiResult<int> UpdateAREAMODEL(UpdateAreaModelInput input)
        {
            var data = _areaRepo.GetEntity(x => x.ID == input.ID);
            if (data == null)
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.NotFound,
                    Message = "数据不存在"
                };
            }
            data.UPDATETIME = DateTime.Now;
            var entity = mapper.Map(input, data);
            int r = _areaRepo.Update(entity);
            return new ApiResult<int>
            {
                Code = r > 0 ? ApiCode.Success : ApiCode.InternalError,
                Message = r > 0 ? "修改成功" : "修改失败",
                ResultData = r
            };
        }
        public ApiResult<int> DeleteAREAMODEL(string id)
        {
            var data = _areaRepo.GetEntity(x => x.ID == id);
            if (data == null)
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.NotFound,
                    Message = "数据不存在"
                };
            }
            data.ISDELETE = true;
            int r = _areaRepo.Update(data);
            return new ApiResult<int>
            {
                Code = r > 0 ? ApiCode.Success : ApiCode.InternalError,
                Message = r > 0 ? "删除成功" : "删除失败",
                ResultData = r
            };
        }
        public ApiPaging<AreaModelOutput> GetAREAMODEL(PageArea page)
        {
            var query = _areaRepo.GetQueryable(x => x.ISDELETE == false);
            if (!string.IsNullOrEmpty(page.AREAID))
            {
                query = query.Where(x => x.AREAID.Contains(page.AREAID));
            }
            if (!string.IsNullOrEmpty(page.AREANAME))
            {
                query = query.Where(x => x.AREANAME.Contains(page.AREANAME));
            }
            if (!string.IsNullOrEmpty(page.WAREHOUSEID))
            {
                query = query.Where(x => x.WAREHOUSEID == (page.WAREHOUSEID));
            }
            //通过warehouseid获取仓库名称
            var linq = query.LeftJoin(_definitionRepo.GetQueryable(x => !x.ISDELETE), (area, definition) => area.WAREHOUSEID == definition.ID)
                                     .Select((area, definition) => new AreaModelOutput
                                     {
                                         ID = area.ID,
                                         CREATETIME = area.CREATETIME,
                                         UPDATETIME = area.UPDATETIME,
                                         AREAID = area.AREAID,
                                         AREANAME = area.AREANAME,
                                         WAREHOUSEID = area.WAREHOUSEID,
                                         WAREHOUSENAME = definition.WAREHOUSENAME,
                                         AREADESC = area.AREADESC
                                     });

            var totalCount = linq.Count();
            var list = linq.OrderByDescending(area => area.ID).Skip((page.PageIndex - 1) * page.PageSize).Take(page.PageSize).ToList();
            return new ApiPaging<AreaModelOutput>
            {
                Code = ApiCode.Success,
                PageDatas = mapper.Map<List<AreaModelOutput>>(list),
                Message = "查询成功",
                TotalCount = totalCount,
                TotalPage = (int)Math.Ceiling(totalCount / (double)page.PageSize)
            };
        }
        public ApiResult<AreaDescOutput> GetAREADESC(string id)
        {
            var data = _areaRepo.GetEntity(x => x.ID == id && x.ISDELETE == false);
            var output = mapper.Map<AreaDescOutput>(data);
            return new ApiResult<AreaDescOutput>
            {
                Code = ApiCode.Success,
                Message = "查询成功",
                ResultData = output
            };
        }
        public ApiResult<List<GetWarehouseAreaIdAndName>> GetWarehouseAreaIdAndName()
        {
            return new ApiResult<List<GetWarehouseAreaIdAndName>>
            {
                Code = ApiCode.Success,
                Message = "查询成功",
                ResultData = _areaRepo.GetQueryable(x => x.ISDELETE == false).Select(x => new GetWarehouseAreaIdAndName
                {
                    ID = x.ID,
                    AREANAME = x.AREANAME
                }).ToList()
            };
        }


        //库位模块
        public ApiResult<int> CreateLOCATIONMODEL(CreateLocationModelInput input)
        {
            //判断是否存在相同的库位编码
            if (_locationRepo.GetEntity(x => x.LOCATIONID == input.LOCATIONID) != null)
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.InternalError,
                    Message = "库位编码已存在",
                    ResultData = 0
                };
            }
            var data = mapper.Map<LOCATION>(input);
            data.ID = YitIdHelper.NextId().ToString();
            data.CREATETIME = DateTime.Now;
            data.ISDELETE = false;
            return new ApiResult<int>
            {
                Code = ApiCode.Success,
                ResultData = _locationRepo.Add(data),
                Message = "添加成功"
            };
        }
        public ApiResult<int> UpdateLOCATIONMODEL(UpdateLocationModelInput input)
        {
            var data = _locationRepo.GetEntity(x => x.ID == input.ID);
            if (data == null)
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.NotFound,
                    Message = "数据不存在"
                };
            }
            data.UPDATETIME = DateTime.Now;
            var entity = mapper.Map(input, data);
            int r = _locationRepo.Update(entity);
            return new ApiResult<int>
            {
                Code = r > 0 ? ApiCode.Success : ApiCode.InternalError,
                Message = r > 0 ? "修改成功" : "修改失败",
                ResultData = r
            };
        }
        public ApiResult<int> DeleteLOCATIONMODEL(string id)
        {
            var data = _locationRepo.GetEntity(x => x.ID == id);
            if (data == null)
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.NotFound,
                    Message = "数据不存在"
                };
            }
            data.ISDELETE = true;
            int r = _locationRepo.Update(data);
            return new ApiResult<int>
            {
                Code = r > 0 ? ApiCode.Success : ApiCode.InternalError,
                Message = r > 0 ? "删除成功" : "删除失败",
                ResultData = r
            };
        }
        public ApiPaging<LocationModelOutput> GetLOCATIONMODEL(PageLocation page)
        {
            var query = _locationRepo.GetQueryable(x => x.ISDELETE == false);
            if (!string.IsNullOrEmpty(page.AREAID))
            {
                query = query.Where(x => x.AREAID == (page.AREAID));
            }
            if (!string.IsNullOrEmpty(page.LOCATIONID))
            {
                query = query.Where(x => x.LOCATIONID.Contains(page.LOCATIONID));
            }
            if (!string.IsNullOrEmpty(page.LOCATIONNAME))
            {
                query = query.Where(x => x.LOCATIONNAME == (page.LOCATIONNAME));
            }
            //通过warehouseid获取仓库名称
            var linq = query.LeftJoin(_areaRepo.GetQueryable(x => !x.ISDELETE), (location, area) => location.AREAID == area.ID)
                                     .Select((location, area) => new LocationModelOutput
                                     {
                                         ID = location.ID,
                                         CREATETIME = location.CREATETIME,
                                         UPDATETIME = location.UPDATETIME,
                                         LOCATIONID = location.LOCATIONID,
                                         LOCATIONNAME = location.LOCATIONNAME,
                                         AREAID = location.AREAID,
                                         AREANAME = area.AREANAME,
                                         LOCATIONDESC = location.LOCATIONDESC
                                     });

            var totalCount = linq.Count();
            var list = linq.OrderByDescending(location => location.ID).Skip((page.PageIndex - 1) * page.PageSize).Take(page.PageSize).ToList();
            return new ApiPaging<LocationModelOutput>
            {
                Code = ApiCode.Success,
                PageDatas = mapper.Map<List<LocationModelOutput>>(list),
                Message = "查询成功",
                TotalCount = totalCount,
                TotalPage = (int)Math.Ceiling(totalCount / (double)page.PageSize)
            };
        }
        public ApiResult<LocationDescOutput> GetLOCATIONDESC(string id)
        {
            var data = _locationRepo.GetEntity(x => x.ID == id && x.ISDELETE == false);
            var output = mapper.Map<LocationDescOutput>(data);
            return new ApiResult<LocationDescOutput>
            {
                Code = ApiCode.Success,
                Message = "查询成功",
                ResultData = output
            };
        }



        //外部标签解析模块
        public ApiResult<int> CreateEXTERNALLABELMODEL(CreateEXTERNALLABELModelInput input)
        {
            //判断是否存在相同的库位编码
            if (_externallabelRepo.GetEntity(x => x.LABELNAME == input.LABELNAME) != null)
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.InternalError,
                    Message = "标签名称已存在",
                    ResultData = 0
                };
            }
            var data = mapper.Map<EXTERNALLABELMODEL>(input);
            data.ID = YitIdHelper.NextId().ToString();
            data.CREATETIME = DateTime.Now;
            data.ISDELETE = false;
            data.SECTIONNUMBER = input.FORMAT.Split(',').Count();
            return new ApiResult<int>
            {
                Code = ApiCode.Success,
                ResultData = _externallabelRepo.Add(data),
                Message = "添加成功"
            };
        }
        public ApiResult<int> UpdateEXTERNALLABELMODEL(UpdateEXTERNALLABELModelInput input)
        {
            var data = _externallabelRepo.GetEntity(x => x.ID == input.ID);
            if (data == null)
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.NotFound,
                    Message = "数据不存在"
                };
            }
            data.UPDATETIME = DateTime.Now;
            var entity = mapper.Map(input, data);
            entity.SECTIONNUMBER = input.FORMAT.Count();
            int r = _externallabelRepo.Update(entity);
            return new ApiResult<int>
            {
                Code = r > 0 ? ApiCode.Success : ApiCode.InternalError,
                Message = r > 0 ? "修改成功" : "修改失败",
                ResultData = r
            };
        }
        public ApiResult<int> DeleteEXTERNALLABELMODEL(string id)
        {
            var data = _externallabelRepo.GetEntity(x => x.ID == id);
            if (data == null)
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.NotFound,
                    Message = "数据不存在"
                };
            }
            data.ISDELETE = true;
            int r = _externallabelRepo.Update(data);
            return new ApiResult<int>
            {
                Code = r > 0 ? ApiCode.Success : ApiCode.InternalError,
                Message = r > 0 ? "删除成功" : "删除失败",
                ResultData = r
            };
        }
        public ApiPaging<EXTERNALLABELModelOutput> GetEXTERNALLABELMODEL(PageEXTERNALLABEL page)
        {
            var query = _externallabelRepo.GetQueryable(x => x.ISDELETE == false);
            if (!string.IsNullOrEmpty(page.LABELNAME))
            {
                query = query.Where(x => x.LABELNAME == (page.LABELNAME));
            }
            if (!string.IsNullOrEmpty(page.Suppiler))
            {
                query = query.Where(x => x.SUPPILY == (page.Suppiler));
            }
            var totalCount = query.Count();
            var list = query.OrderByDescending(x => x.ID).Skip((page.PageIndex - 1) * page.PageSize).Take(page.PageSize).ToList();
            return new ApiPaging<EXTERNALLABELModelOutput>
            {
                Code = ApiCode.Success,
                PageDatas = mapper.Map<List<EXTERNALLABELModelOutput>>(list),
                Message = "查询成功",
                TotalCount = totalCount,
                TotalPage = (int)Math.Ceiling(totalCount / (double)page.PageSize)
            };
        }
        public ApiResult<EXTERNALLABELDescOutput> GetEXTERNALLABELDESC(string id)
        {
            var data = _externallabelRepo.GetEntity(x => x.ID == id && x.ISDELETE == false);
            var output = mapper.Map<EXTERNALLABELDescOutput>(data);
            return new ApiResult<EXTERNALLABELDescOutput>
            {
                Code = ApiCode.Success,
                Message = "查询成功",
                ResultData = output
            };
        }


        //仓库入出库记录
        public ApiResult<int> CreateIOWAREHOUSERECORDMODEL(CreateIOWAREHOUSERECORDModelInput input)
        {
            using (var scope = new TransactionScope(TransactionScopeOption.Required,new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted },TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    // 更新库存实体
                    var made_up_articles = _mduRepo.GetEntity(x => x.Made_UpArticlesCode == input.BARCODE);
                    if (made_up_articles == null)
                    {
                        return new ApiResult<int>
                        {
                            Code = ApiCode.ParameterError,
                            ResultData = 0,
                            Message = "暂无成品，请前往添加！"
                        };
                    }
                    if (input.DOCUMENTTYPE == "入库")
                    {
                        made_up_articles.Num += input.NUM;
                    }
                    else if (input.DOCUMENTTYPE == "出库")
                    {
                        if (input.NUM > made_up_articles.Num)
                        {
                            return new ApiResult<int>
                            {
                                Code = ApiCode.InternalError,
                                ResultData = 0,
                                Message = "库存不足，无法出库！"
                            };
                        }

                        made_up_articles.Num -= input.NUM;
                    }

                    // 执行更新
                    var madResult = _mduRepo.Update(made_up_articles);

                    // 创建出入库记录
                    var data = mapper.Map<IOWAREHOUSERECORDMODEL>(input);
                    data.ID = YitIdHelper.NextId().ToString();
                    data.CREATETIME = DateTime.Now;
                    data.OPERATETIME = DateTime.Now;
                    data.OPERATEUSERNAME = "admin";
                    data.ORDERNUMBER = GetCode("出入库").Result.ResultData;
                    data.ISDELETE = false;

                    var ioResult = _ioRepo.Add(data);

                    // 提交事务
                    scope.Complete();

                    return new ApiResult<int>
                    {
                        Code = ApiCode.Success,
                        ResultData = ioResult,
                        Message = "添加成功"
                    };
                }
                catch (Exception ex)
                {
                    // 回滚事务
                    return new ApiResult<int>
                    {
                        Code = ApiCode.InternalError,
                        Message = $"操作失败: {ex.Message}"
                    };
                }
            }
        }
        public ApiResult<int> DeleteIOWAREHOUSERECORDMODEL(string id)
        {
            var data = _ioRepo.GetEntity(x => x.ID == id);
            if (data == null)
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.NotFound,
                    Message = "数据不存在"
                };
            }
            data.ISDELETE = true;
            int r = _ioRepo.Update(data);
            return new ApiResult<int>
            {
                Code = r > 0 ? ApiCode.Success : ApiCode.InternalError,
                Message = r > 0 ? "删除成功" : "删除失败",
                ResultData = r
            };
        }
        public ApiPaging<IOWAREHOUSERECORDModelOutput> GetIOWAREHOUSERECORDMODEL(PageIOWAREHOUSERECORD page)
        {
            var query = _ioRepo.GetQueryable(x => x.ISDELETE == false);
            if (!string.IsNullOrEmpty(page.BARCODE))
            {
                query = query.Where(x => x.BARCODE == (page.BARCODE));
            }
            if (!string.IsNullOrEmpty(page.ORDERNUMBER))
            {
                query = query.Where(x => x.ORDERNUMBER == (page.ORDERNUMBER));
            }
            var totalCount = query.Count();
            var list = query.OrderByDescending(x => x.ID).Skip((page.PageIndex - 1) * page.PageSize).Take(page.PageSize).ToList();
            return new ApiPaging<IOWAREHOUSERECORDModelOutput>
            {
                Code = ApiCode.Success,
                PageDatas = mapper.Map<List<IOWAREHOUSERECORDModelOutput>>(list),
                Message = "查询成功",
                TotalCount = totalCount,
                TotalPage = (int)Math.Ceiling(totalCount / (double)page.PageSize)
            };
        }

        /// <summary>
        /// 编码生成器
        /// </summary>
        /// <param name="codeType"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<string>> GetCode(string codeType)
        {
            var code = "";

            if (codeType == "仓库")
            {
                var networkTimeResult = await GetNetworkTimeAsync();
                code = "JNZG-CK-" + networkTimeResult.ToString("yyyyMMddHHmmss");

            }
            if (codeType == "库区")
            {
                var networkTimeResult = await GetNetworkTimeAsync();
                code = "JNZG-KQ-" + networkTimeResult.ToString("yyyyMMddHHmmss");

            }
            if (codeType == "库位")
            {
                var networkTimeResult = await GetNetworkTimeAsync();
                code = "JNZG-KW-" + networkTimeResult.ToString("yyyyMMddHHmmss");

            }
            if (codeType == "标签解析")
            {
                var networkTimeResult = await GetNetworkTimeAsync();
                code = "JNZG-BQ-" + networkTimeResult.ToString("yyyyMMddHHmmss");

            }
            if (codeType == "出入库")
            {
                var networkTimeResult = await GetNetworkTimeAsync();
                code = "JNZG-IO-" + networkTimeResult.ToString("yyyyMMddHHmmss");

            }
            //获取当前网络时间
            Console.WriteLine(code);
            return new ApiResult<string>
            {
                Code = ApiCode.Success,
                ResultData = code,
                Message = "获取成功"
            };

        }
        /// <summary>
        /// 获取网络时间
        /// </summary>
        /// <returns></returns>
        public static async Task<DateTime> GetNetworkTimeAsync()
        {
            try
            {
                //default Windows time server
                //用域名获取时候用这里
                //string ntpServer = "time.windows.com";

                // NTP message size - 16 bytes of the digest (RFC 2030)
                var ntpData = new byte[48];
                //Setting the Leap Indicator, Version Number and Mode values
                ntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode) {52.231.114.183
                                   //用域名获取时候用这里
                                   //var addresses = Dns.GetHostEntry(ntpServer).AddressList;
                IPAddress[] IPAddressList = new IPAddress[1];
                //配置时间服务器IP
                IPAddress address = new IPAddress(new byte[] { 192, 168, 1, 1 });  // NTP IP 地址
                IPAddressList[0] = address;
                //The UDP port number assigned to NTP is 123
                var ipEndPoint = new IPEndPoint(IPAddressList[0], Convert.ToInt32(123));
                //NTP uses UDP
                var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                socket.Connect(ipEndPoint);
                //Stops code hang if NTP is blocked
                socket.ReceiveTimeout = 1000;

                socket.Send(ntpData);
                socket.Receive(ntpData);
                socket.Close();
                //Offset to get to the "Transmit Timestamp" field (time at which the reply
                //departed the server for the client, in 64-bit timestamp format."
                const byte serverReplyTime = 40;

                //Get the seconds part
                ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);
                //Get the seconds fraction
                ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);

                //Convert From big-endian to little-endian
                intPart = SwapEndianness(intPart);
                fractPart = SwapEndianness(fractPart);
                var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);

                //**UTC** time
                var networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);
                return networkDateTime.ToLocalTime();
            }
            catch (Exception ex)
            {
                return DateTime.Now;
            }
        }
        /// <summary>
        /// 强制按大端解析
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        static uint SwapEndianness(ulong x)
        {
            return (uint)(((x & 0x000000ff) << 24) +
            ((x & 0x0000ff00) << 8) +
            ((x & 0x00ff0000) >> 8) +
            ((x & 0xff000000) >> 24));
        }

        public ApiResult<int> CreateMade_UpArticlesModel(CreateMade_UpArticlesModelInput input)
        {
            var isnull = _mduRepo.GetEntity(x => x.Made_UpArticlesCode == input.Made_UpArticlesCode);
            if (isnull != null)
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.InternalError,
                    ResultData = 0,
                    Message = "已有该成品，请勿重复添加！"
                };
            }
            var data = mapper.Map<Made_UpArticlesModel>(input);
            data.ID = YitIdHelper.NextId().ToString();
            data.CREATETIME = DateTime.Now;
            data.CREATEDUSERNAME = "admin";
            data.ISDELETE = false;
            return new ApiResult<int>
            {
                Code = ApiCode.Success,
                ResultData = _mduRepo.Add(data),
                Message = "添加成功"
            };
        }

        public ApiResult<int> DeleteMade_UpArticlesModel(string id)
        {
            var data = _mduRepo.GetEntity(x => x.ID == id);
            if (data == null)
            {
                return new ApiResult<int>
                {
                    Code = ApiCode.NotFound,
                    Message = "数据不存在"
                };
            }
            data.ISDELETE = true;
            int r = _mduRepo.Update(data);
            return new ApiResult<int>
            {
                Code = r > 0 ? ApiCode.Success : ApiCode.InternalError,
                Message = r > 0 ? "删除成功" : "删除失败",
                ResultData = r
            };
        }

        public ApiPaging<Made_UpArticlesModelOutput> GetMade_UpArticlesModel(PageMade_UpArticlesModel page)
        {
            var query = _mduRepo.GetQueryable(x => x.ISDELETE == false);
            if (!string.IsNullOrEmpty(page.Made_UpArticlesCode))
            {
                query = query.Where(x => x.Made_UpArticlesCode == (page.Made_UpArticlesCode));
            }
            if (!string.IsNullOrEmpty(page.Made_UpArticlesName))
            {
                query = query.Where(x => x.Made_UpArticlesName == (page.Made_UpArticlesName));
            }
            var totalCount = query.Count();
            var list = query.OrderByDescending(x => x.ID).Skip((page.PageIndex - 1) * page.PageSize).Take(page.PageSize).ToList();
            return new ApiPaging<Made_UpArticlesModelOutput>
            {
                Code = ApiCode.Success,
                PageDatas = mapper.Map<List<Made_UpArticlesModelOutput>>(list),
                Message = "查询成功",
                TotalCount = totalCount,
                TotalPage = (int)Math.Ceiling(totalCount / (double)page.PageSize)
            };
        }
    }
}
